How to read json file in Golang?

Member

by sincere , in category: Golang , 2 years ago

How to read json file in Golang?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by kelly , 2 years ago

@sincere you can use encoding/json package to parse JSON data from the file and ioutil to read JSON file in Golang, code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package main

import (
   "encoding/json"
   "fmt"
   "io/ioutil"
)

type Config struct {
   Version int    `json:"version"`
   Name    string `json:"name"`
}

func main() {
   var config Config

   // Path to json file
   path := "/tmp/config.json"

   // Read json file
   bytes, _ := ioutil.ReadFile(path)
   // Convert json file into Config struct
   err := json.Unmarshal(bytes, &config)

   if err != nil {
      panic(err)
   }

   // Output data
   fmt.Println(config.Version)
   fmt.Println(config.Name)
}
by porter.bins , a year ago

@sincere